<?php
class CommonAction extends Action
{
    protected $tokenid;

    public function __construct()
    {
        parent::__construct();

        /*$servername=$_SERVER['SERVER_NAME']; //获取本站域名

        $sub_from=$_SERVER["HTTP_REFERER"]; //获取来源的referer

        $sub_len=strlen($servername); //计算本站域名的长度

        $checkfrom=substr($sub_from,7,$sub_len); //截取来源域名

        if($checkfrom!=$servername){ //假如截取的来源域名不等于本站域名,则终止.

            echo("数据来源有误！请从本站提交！");

            exit;

        }*/
        vendor('pinyin.src.Pinyin');
        session_start();
        $member_info=session('member_info');
        $this->assign('member_info',$member_info);
        getbrowser();//浏览器判断
        $user_info =session('member_info');
        if (!$user_info['m_id']) {
            if (IS_AJAX) {
                $this->error('登陆失效，请点击确定重新登陆！', '/', 10);
            }
            exit('<script language="javascript">top.location.href="/"</script>');
        }else{
            session(array('member_info'=>$member_info,'expire'=>3600));
        }
        import("ORG.Util.Auth");
        $auth=new Auth();
        if (MODULE_NAME !== 'Index') {
            $url = getUrl();
            $result = $auth->check($url, $user_info['m_id']);
            if ($result === false) {
                if (IS_AJAX) {
                    $this->ajaxError('没有权限!');
                } else {
                    $this->error('没有权限!');
                }
            }
        }
    }

    /**
     * @auth:leishaofa
     * @date:2017-07-21
     * @efect:随机生成手机号
     */
    public function randomPone($num){
        $list=[];
        $arr = array(
            130,131,132,133,134,135,136,137,138,139,
            144,147,
            150,151,152,153,155,156,157,158,159,
            176,177,178,
            180,181,182,183,184,185,186,187,188,189,
        );

        $x=0;
        do {
            $randompone=$arr[array_rand($arr)].mt_rand(1000,9999).mt_rand(1000,9999);
            if(in_array($randompone,$list)){
                $this->randomPone($num,$list);
            }else{
                array_push($list,$randompone);
                $x++;
            }
        } while ($x<$num);
        return $list;

    }


    public function randomaccount($start_time,$end_time,$name){
        $info='';
        $start_time = strtotime($start_time);
        $end_time = strtotime($end_time);
        $info['birthday']=date('Y-m-d', mt_rand($end_time,$start_time));
        $info['sex']=rand(1,2);//1男 2：女
        $info['eamil']= substr(date('Ynj',strtotime($info['birthday'])),2).str_pad(mt_rand(1, 999), 3, '0', STR_PAD_LEFT);
        return $info;

    }




    /**
     * 错误返回
     * @param string $msg
     * @param array $fields
     */
    protected function ajaxError($msg = '', $fields = array())
    {
        header('Content-Type:application/json; charset=utf-8');
        $data = array('code' => '4001', 'msg' => $msg, 'fields' => $fields);
        echo json_encode($data);
        exit;
    }

    /**
     * 成功返回
     * @param $msg
     * @param array $_data
     */
    protected function ajaxSuccess($msg, $_data = array())
    {
        header('Content-Type:application/json; charset=utf-8');
        $data = array('code' => '101', 'msg' => $msg, 'data' => $_data);
        echo json_encode($data);
        exit;
    }


    /**
     * @auth:leishaofa
     * @data:20170714
     * @parame:通过百度坐标获取地址信息
     * $lat	纬度坐标
     * $lng经度坐标
     */
    protected  function getbaiduaddress($lat,$lng){
        if(empty($lat) || empty($lng)){
            return false;
        }
        $url="http://api.map.baidu.com/geocoder/v2/?location=".$lat.",".$lng."&output=json&ak=".C('BAIDUAK');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);    //表示需要response header
        curl_setopt($ch, CURLOPT_NOBODY, false); //表示需要response body
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
        curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);
        $result = curl_exec($ch);

        return $result;
    }


    /**
     * 坐标绘制矩形，获取矩形对应的百度坐标
    */
    protected  function extendsbaidu($baidulbs,$krm){
        $bdgps=explode(',',BD09LLtoWGS84($baidulbs));//百度坐标转GPS坐标
        $bdgps=resultmap($bdgps[0],$bdgps[1],$krm);//通过GPS坐标绘制矩形
        //调用百度GPS坐标装换百度坐标
        $url="http://api.map.baidu.com/geoconv/v1/?coords=".$bdgps['left-top']['lng'].",".$bdgps['left-top']['lat'].";".$bdgps['right-top']['lng'].",".$bdgps['right-top']['lat'].";".$bdgps['left-bottom']['lng'].",".$bdgps['left-bottom']['lat'].";".$bdgps['right-bottom']['lng'].",".$bdgps['right-bottom']['lat']."&ak=".C('BAIDUAK');

        $wgsToBaidu = $this->getcurl($url);
        $wgsToBaidu =$wgsToBaidu['result'];
        return $wgsToBaidu;
    }


    /**
     * @auth:leishaofa
     * @data:20170713
     * @parame:通过坐标poi地址附近信息
     * $baidul坐标
     * $key住宅区,便利店,超市,购物中心,写字楼等
     * query=写字楼
     * //bounds=30.553743522788,114.26426327433,30.574285178536,114.28522989338
     * //page_num=1
     * $page第几页
     * */
    protected function getbaidupoi($wgsToBaidu,$key,$page){
        //poi搜索
        $url="http://api.map.baidu.com/place/v2/search?query=".$key."&bounds=".$wgsToBaidu[2]['y'].",".$wgsToBaidu[2]['x'].",".$wgsToBaidu[1]['y'].",".$wgsToBaidu[1]['x']."&output=json&page_size=20&page_num=".$page."&ak=".C('BAIDUAK');
        return $this->getcurl($url);
    }

    private function getcurl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_NOBODY, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
        curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);
        $result = curl_exec($ch);
        $result=json_decode($result,true);
        return $result;
    }
    protected function gethttpscurl($curl){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $curl);
        curl_setopt($curl, CURLOPT_HEADER, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($curl);
       return $data;

    }
    /**
     * @auth:leishaofa
     * @date:20170915
     * @efect:获取美团云可用机房信息
     * @parame:$data:服务商信息     array()
     * @parame:$actiondata :调用方法以及方法参数   array()
    */
    public function meituanyunComputerRoom($data,$actiondata){
        $region = array('华北1' =>'Beijing', '华东1' =>'EastChina1');
        $resultdata='';
        foreach ($region as $key=>$val){
            $data['Region']=$val;
            $result=$this->meituanyun($data,$actiondata)['DescribeAvailabilityZonesResponse']['AvailabilityZoneSet']['AvailabilityZone'];
            foreach ($result as $v) {
                if($v['Status'] == 'enable') {
                    $resultdata[$val . "=>" .$v['availabilityZoneId']] = $key . "=>" . $v['availabilityZoneName_CN'];
                }
            }
        }
        return $resultdata;
    }




    /**
     * @auth:leishaofa
     * @date:2017803
     * @efect:私有方法美团云调用方法
     * @parame:$data:服务商信息     array()
     * @parame:$actiondata :调用方法以及方法参数   array()
     */
    public function meituanyun($data,$actiondata){
        $key = $data['ser_key'];//key
        $secret = $data['ser_secret'];//secret
        $posturl=trim($data['ser_url']);//api地址
        $signurl=parse_url($posturl);//拆分后的api地址
        $time=str_replace('+','.',date(DATE_ISO8601))."Z";
        $data=array('Format'=>'json','AWSAccessKeyId'=>$key,'SignatureVersion'=>2,'Timestamp'=>$time,'Region'=>empty($data['Region'])?'NorthChina1':$data['Region'],'SignatureMethod'=>HmacSHA256);//固定请求参数

        $data=array_merge($data,$actiondata);//合并组装所有请求参数
        ksort($data);//参数名称的字典顺序排序（重小到大）
        $strdata=http_build_query($data);//x-www-form-urlencoded数据组装
        $hashdata="POST\n".$signurl['host']."\n".$signurl['path']."\n".$strdata;//组装签名内容
        $sign= base64_encode( hash_hmac('sha256', $hashdata, $secret,true));//获取签名以HmacSHA256 算法进行Hash后，进行base64编码
        $data['Signature']=$sign;
        $postData = http_build_query($data);//x-www-form-urlencoded数据组装
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $posturl);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);//允许重定向吧
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));//x-www-form-urlencoded编码
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); // Post提交的数据包
        //curl_setopt($curl, CURLOPT_HEADER, 1);//返回请求head头
        //curl_setopt($curl, CURLOPT_NOBODY, 1);//不返回body部分内容
        //curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        $data = curl_exec($curl);
        curl_close($curl);
        return json_decode($data,true);
    }

    /**
     * @auth:leishaofa
     * @date:2017803
     * @efect:腾讯
     * @parame:$data:服务商信息     array()
     * @parame:$actiondata :调用方法以及方法参数   array()
     */
    public function tencat($server,$action,$actiondata){
        Vendor('QcloudApi.QcloudApi');
        $config = array(
            'SecretId'      => $server['ser_key'],
            'SecretKey'     => $server['ser_secret'],
            'RequestMethod'  => 'GET',
            'DefaultRegion' => empty($server['Region'])?'gz':$server['Region']
        );
        $cvm = QcloudApi::load($server['model'], $config);
        $package = array('SignatureMethod' =>'HmacSHA256');
        $package=array_merge($package,$actiondata);//合并组装所有请求参数
        ksort($package);
        $a=$cvm->$action($package);

   //      $a = $cvm->generateUrl($action,$package);

       /* if ($a === false) {
            $error = $cvm->getError();
            echo "Error code:" . $error->getCode() . ".\n";
            echo "message:" . $error->getMessage() . ".\n";
            echo "ext:" . var_export($error->getExt(), true) . ".\n";
        } else {
            var_dump($a);
        }*/
        //echo "\nRequest :" . $cvm->getLastRequest();
        return  json_decode($cvm->getLastResponse(),true);
    }


    /**
     * @auth:leishaofa
     * @date:2017818
     * @efect:私有方法阿里云调用方法
     * @parame:$data:服务商信息     array()
     * @parame:$actiondata :调用方法以及方法参数   array()
     */
    public function ali($server,$action,$actiondata){
        Vendor('AliyunAPI.aliyun-php-sdk-core.Config');
        $clientProfile =DefaultProfile::getProfile($server['Region'], $server['ser_key'],$server['ser_secret']);
        $client = new DefaultAcsClient($clientProfile);
       // $request = new \Ecs\Request\V20140526\StopInstanceRequest();
       // $request->setInstanceId();

        $request = new $action();//DescribeInstanceTypes();
        // $request->setFormat('json');
        if(is_array($actiondata) && !empty($actiondata)){
            foreach ($actiondata as $key=>$val){
                $request->$key($val);
            }
        }
        # 发起请求并处理返回
        try {
            $response = $client->getAcsResponse($request);
            return $response;
        } catch(ServerException $e) {
            return "Error: " . $e->getErrorCode() . " Message: " . $e->getMessage() . "\n";
        } catch(ClientException $e) {
            return "Error: " . $e->getErrorCode() . " Message: " . $e->getMessage() . "\n";
        }
    }


    protected function update_config($new_config, $config_file = '') {
        !is_file($config_file) ? $config_file : CONF_PATH . '/config.php';

        if (is_writable($config_file)) {
            $config = require $config_file;

            $config = array_merge($config, $new_config);
            file_put_contents($config_file, "<?php \nreturn " . stripslashes(var_export($config, true)) . ";", LOCK_EX);
            @unlink(RUNTIME_FILE);
            return true;
        } else {
            return false;
        }
    }
    /**
     * @auth:leishaofa
     * @date:20417804
     * @efect:获取指定类型的主机类型
     * @parame:$data:服务商信息 参考美团云控制台API     array()
     * @parame:$types:主机类型，null查询所有参考美团控制台左侧主机类型对应如下，：ssd，mebs，Rabbitmq，auth（云主机），gpu	，BDS， Redis，MongoDB，RDS，Memcached，SDS，onevirt（独享云主机）
     * @parame:$Limit,$Offset对应美团API方法DescribeInstanceTypes参数说明
     * @return:array()//返回参数美团API方法DescribeInstanceTypes参数说明
     */
    public function gettypehost($data,$types,$Limit,$Offset){
        $types=explode('=>',$types);
        $data['Region']=$types[0];
        $actiondata=array('Action'=>'DescribeInstanceTypes');
        if(is_numeric($Limit)&& !empty($Limit)){
            $actiondata['Limit']=$Limit;
        }
        if(is_numeric($Offset)&& !empty($Offset)){
            $actiondata['Offset']=$Offset;
        }
        $resultdata=$this->meituanyun($data,$actiondata)['DescribeInstanceTypesResponse']['InstanceTypeSet']['InstanceType'];
        $listdata=[];
        $types = 'auth';
        //除法放里面，当取某一个类型数据更快
        foreach ($resultdata as $key=>$val){
            $type=explode('::',$val['instanceType']);
            if(!empty($types) && $types == 'auth' && empty($type[1])){
                $val['gb'] = bcdiv($val['memory'], '1024', '0');
                if($val['instanceType']=='C'.$val['cpu'].'_M'.$val['gb']) {
                    $listdata['auth'][$val['cpu']][] = $val;
                }
            }elseif(!empty($types) && $types != 'auth' && !empty($type[1]) && $types==trim($type[0])){
                $val['gb']=bcdiv($val['memory'], '1024', '0');
                $listdata[$type[0]][$val['cpu']][] = $val;
            }elseif (empty($types)){
                $val['gb']=bcdiv($val['memory'], '1024', '0');
                if(isset($type[1]) && !empty($type[1])) {
                    $listdata[$type[0]][$val['cpu']][] = $val;
                }else{
                    $listdata['auth'][$val['cpu']][] = $val;
                }
            }
        }
        unset($resultdata);
        return $listdata;
    }


    /**
     * tp日志
     * @param $data
     */
    public function Log($data)
    {
        Log::record(str_repeat("+",20) . 'LOG' . " Start" . str_repeat("+",20),Log::DEBUG);
        if(is_string($data)){
            Log::record($data,Log::DEBUG);
        }else{
            Log::record(json_encode($data),Log::DEBUG);
        }
        Log::record(str_repeat("+",20) . 'LOG' . " End" . str_repeat("+",20),Log::DEBUG);
    }

}